import api from '@/api'
import {NOT_ALLOWED_TYPE_ID} from '@/config/constant'

export default {
  namespaced: true,
  
  state: {
    userInfo: {},
    testLogin: false
  },
  
  getters: {
    roleType(state) {
      return state.userInfo.type || null
    },
    
    userId(state) {
      return state.userInfo.id || null
    },
    
    roleId(state) {
      return state.userInfo.roleId || null
    },
    
    userName(state) {
      return state.userInfo.name || ''
    },
    
    orgName(state) {
      return state.userInfo.orgName || ''
    },
    
    token(state) {
      return state.userInfo.token || ''
    },
    
    isLogin(state) {
      return !!(state.testLogin || state?.userInfo?.token)
    },
    
    orgCode(state) {
      return state.userInfo.orgCode || ''
    }
  },
  
  mutations: {
    SET_LOGIN(state, payload) {
      state.userInfo = payload
    },
    
    SET_LOGOUT(state) {
      state.userInfo = {}
    },
    
    SET_TEST_LOGIN(state) {
      state.testLogin = true
    },
  },
  
  actions: {
    login({commit, dispatch}, payload) {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await api.system.user.login(payload)
          if (NOT_ALLOWED_TYPE_ID.includes(res.data.type)) {
            reject('该账号无权限登录系统')
          } else {
            commit('SET_LOGIN', res.data)
            resolve()
          }
        } catch (err) {
          reject(err)
        }
      })
    },
    
    logout({commit}) {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await api.system.user.logout()
          if (res) {
            commit('SET_LOGOUT')
            resolve(res.data)
          }
        } catch (err) {
          commit('SET_LOGOUT')
          reject(err)
        }
      })
    }
  }
}
